import iButton from '@/components/carGoods/i-button.vue'
import carInfoHeader from '@/components/afterSales/carInfoHeader.vue'
import addGoodsPopup from './components/addGoods-popup.vue'
import editServePopup from './components/edit-serve-popup.vue'
import installModePopup from './components/install-mode-popup.vue'

// 左滑操作组件
import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'

// 生成二维码插件
import tkiQrcode from '@/components/tki-qrcode/tki-qrcode.vue'

export default {
  components: {
    iButton,
    carInfoHeader,
    addGoodsPopup,
    editServePopup,
    installModePopup,
    tkiQrcode, // 生成二维码插件
    uniSwipeAction,
    uniSwipeActionItem,
  },

  data() {
    return {
      id: 1,
      isSubmit: false, // 是否已提交
      groupList: [], //从福利包中选中的商品和服务
      isPackage: 2, //1是福利包进入 2 是优惠券进入
      // 手动添加实物产品列表
      productList: [],

      // 手动添加施工服务列表
      serveList: [],

      serveIsPackage: false, //编辑的服务是否从福利包进入

      installMode: {
        id: 0,
        name: '到店安装',
      }, // 安装方式的值

      goodsShow: false, // 显示添加商品弹框
      serveShow: false, // 显示编辑服务弹框
      installModeShow: false, // 显示安装方式弹框
      // 金额价格部分
      priceDataCont: {
        goodsPrice: 0.0,
        servePrice: 0.0,
        couponsMoney: 0.0,
        couponsMoney2: 0.0,
        totalPrice: 0.0,
        allMoney: 0.0,
      },
      // 确认信息
      confirmInfo: {
        guideName: '', // 导购员确认
        userDate: '',
        userName: '', // 客户签名确认
        orderNo: '', // 订单号
      },
      couponAllMoney: 0, // 优惠总金额
      sumPrice: 0, //实付价格

      coupons: {}, // 优惠卡券
      isSelectedCoupons: false, // 是否选择了优惠卡券
      hasCoupon: false, // 客户是否含有优惠卡券

      remark: '', // 备注
      // 支付收款码标题
      tabPayTitleList: [
        {
          name: '支付宝支付',
        },
        {
          name: '微信支付',
        },
        {
          name: '现金支付',
        },
      ],
      payTitleIndex: 0, // 当前收款码
      detailData: {}, // 详情所有的数据
      payqrImg: [], // 生成的支付二维码的图片
      rightOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#EB5C02',
          },
        },
      ],

      couponName: '', //套餐卡名称

      billImg: '/static/img/afterSales/piao.png', //收据
      billRemark: '', //收据备注

      qrcode:
        '',
    }
  },

  computed: {
    // 金额价格部分
    priceData: {
      get() {
        // 商品和服务金额
        let obj = {
          goodsPrice: this.sumFn('sale_Price', true, false), //商品金额
          servePrice: this.sumFn('sale_Price', false, true), //服务金额
          couponsMoney: this.sumFn('discountAmount', true, true), //套餐卡优惠金额
          couponsMoney2: 0.0, //优惠券优惠金额
        }
        // 合计金额，减去优惠金额
        obj.couponAllMoney = obj.couponsMoney + obj.couponsMoney2
        obj.allMoney = obj.goodsPrice + obj.servePrice
        obj.totalPrice = (
          obj.goodsPrice +
          obj.servePrice +
          obj.couponsMoney +
          obj.couponsMoney2
        ).toFixed(2)
        return obj
      },
      set(v) {
        this.priceDataCont = v
      },
    },

    // 显示优惠券
    couponData() {
      // 是否有可用优惠券
      if (this.hasCoupon) {
        // 是否选择了优惠券
        if (this.isSelectedCoupons) {
          return this.coupons.coupon_name
        } else {
          return '选择优惠卡券'
        }
      } else {
        return '无可用优惠卡券'
      }
    },

    // 显示套餐卡
    setMenuData() {
      // 是否有可用套餐卡
      if (this.hasCoupon) {
        // 是否选择了优惠券
        if (this.isSelectedCoupons) {
          return this.coupons.coupon_name
        } else {
          return '选择套餐卡'
        }
      } else {
        return '无可用套餐卡'
      }
    },

    hasProduct() {
      let hasProduct = false,
        hasServe = false
      this.groupList.forEach((item1) => {
        item1.goodsServiceList.forEach((item2) => {
          if (item2.isGoods) {
            hasProduct = true
          } else {
            hasServe = true
          }
          if (hasProduct && hasServe) {
            return [hasProduct, hasServe]
          }
        })
      })
      return [hasProduct, hasServe]
    },
  },

  filters: {
    // 过滤订单状态显示文字
    handleStatus(val) {
      let status = {
        0: '待提交',
        1: '待付款',
        2: '待施工',
      }
      return status[val]
    },

    // 处理金额数字小数点精度
    handleNumFloat(val) {
      return parseFloat(val)
    },
  },

  onLoad(e) {
    this.id = e.id
    this.groupList = this.$store.state.afterSales.groupList
    this.couponName = e.name
    this.isPackage = Number(e.isPackage)
    // if (e.isSubmit) {
    //   this.isSubmit = parseInt(e.isSubmit) !== 1
    //   uni.setNavigationBarTitle({
    //     title: '报价单-已生成订单',
    //   })
    // } else {
    //   this.isSubmit = false
    // }
    this.confirmInfo.guideName = this.$store.state.userInfoDetail.user.userName
    uni.$on('userConfirm', (date) => {
      this.confirmInfo.userName = date.userName
    })

    // 选择了优惠券，处理优惠券到对应的商品或服务里
    // 回调参数data：优惠金额相关数据，coupon：选择的优惠券
    uni.$once('couponChange', ({ data, coupon }) => {
      console.log('选择的优惠券', { data, coupon })
      // 产品列表 添加优惠券
      // this.productList.map((item, index) => {
      //   item.couponId = data.goodsList[index].coupon_Details_Id
      //   item.couponMoney = data.goodsList[index].discountAmount
      // })
      // // 服务列表 添加优惠券
      // this.serveList.map((item, index) => {
      //   item.couponId = data.serviceFeeList[index].coupon_Details_Id
      //   item.couponMoney = data.serviceFeeList[index].discountAmount
      // })
      // // 添加优惠金额
      // this.priceDataCont.couponsAllMoney = data.discountTotalAmount
      // this.couponAllMoney = data.discountTotalAmount
      // this.coupons = coupon
      // this.isSelectedCoupons = true
    })
    // this.getDetailData()
    this.getCouponList()
  },

  beforeDestroy() {
    uni.$off('couponChange')
  },

  methods: {
    // 根据商品匹配相关服务
    async GetServiceFeeByGoods(list) {
      let data = {
        configuration_Id: this.$store.state.afterSales.carInfo.carId + '',
        // 过滤有服务才传入对应参数
        getServiceFeeGoodsList: list
          .filter((item) => !!item.maintenance_Type_Id)
          .map((item) => ({
            maintenance_Type_Id: item.maintenance_Type_Id,
            maintenance_Goods_Id: item.id,
            count: item.amount,
          })),
      }
      try {
        const res = await this.$api.afterSales.GetServiceFeeByGoods(data)
        // 添加对应的key名
        let list = res.data.map((item) => ({
          ...item,
          couponId: null,
          couponMoney: 0,
          serviceCount: item.serviceNum,
          serviceId: item.maintenance_Type_Id,
          serviceName: item.service_Name,
          servicePrice: item.service_Price,
        }))
        this.serveList = [...this.serveList, ...list]
        console.log(res.data)
      } catch (err) {
        console.log(err)
      }
    },

    // 确定添加商品
    addGoodsChange({ type, data }) {
      console.log('添加商品', type, data)
      // type为true则是点击确定按钮，false为继续添加商品
      if (type) {
        this.goodsShow = false
        let list = data.map((item) => ({
          ...item,
          productCount: item.amount,
          productId: item.id,
          productName: item.goods_Name,
          inPrice: item.in_Price,
          productPrice: item.isVisualGoods ? 0 : item.sale_Price,
          addRange: item.added_Rate,
          goodsTypeId: item.maintenance_Type_Id,
        }))
        this.productList = this.productList.concat(list)
        this.GetServiceFeeByGoods(list)
        // console.log('确定，商品信息', list)
      } else {
        console.log('继续添加，商品信息', list)
      }
    },

    // 打开服务弹框
    servePopupOpen(item, index, index1, isMustAll, serveIsPackage) {
      // 已生成订单状态，就不能打开服务弹框更改了
      if (this.isSubmit) return
      this.serveIsPackage = serveIsPackage
      this.serveShow = true
      this.$nextTick(() => {
        this.$refs.serve.loadData(item, index, index1, isMustAll)
      })
    },

    // 编辑服务确定/取消
    editServeChange({ type, data, index, index1, isMustAll }) {
      // type为true则是点击确定按钮，false为继续添加商品
      this.serveShow = false
      if (type) {
        console.log('确定，修改服务信息', data)
        if (this.serveIsPackage) {
          if (isMustAll) {
            this.groupList[index].goodsServiceList.forEach((item1) => {
              item1.count = data.count
              item1.name = data.name
              item1.sale_Price = data.price
            })
          } else {
            this.groupList[index].goodsServiceList[index1].count = data.count
            this.groupList[index].goodsServiceList[index1].name = data.name
            this.groupList[index].goodsServiceList[index1].sale_Price =
              data.price
          }
        } else {
          this.serveList[index].serviceCount = data.count
          this.serveList[index].servicePrice = data.price
          this.serveList[index].serviceName = data.name
        }
      }
    },

    // 减
    less(item, index, isMustAll) {
      if (item.count <= 1) return
      if (isMustAll) {
        this.groupList[index].goodsServiceList.forEach((item1) => {
          item1.count -= 1
        })
      } else {
        item.count -= 1
      }
    },

    // 加
    add(item, index, isMustAll) {
      if (isMustAll) {
        this.groupList[index].goodsServiceList.forEach((item1) => {
          item1.count += 1
        })
      } else {
        item.count += 1
      }
    },

    // 减-手动选择商品
    less2(item) {
      if (item.productCount <= 1) return
      item.productCount -= 1
    },

    // 加-手动选择商品
    add2(item) {
      item.productCount += 1
    },

    // 左滑删除商品项
    delChange(index1, index, isMustAll, isPackage) {
      // 需延迟移除数组项
      setTimeout(() => {
        if (isPackage) {
          if (
            isMustAll ||
            this.groupList[index].goodsServiceList.length === 1
          ) {
            this.groupList.splice(index, 1)
          } else {
            this.groupList[index].goodsServiceList(index1, 1)
          }
        } else {
          this.productList.splice(index1, 1)
        }
      }, 100)
    },

    // 计算商品金额、服务金额的各的总价
    sumFn(priceKey, isGoods, isSreve) {
      let sum = 0
      this.groupList.forEach((list1) => {
        list1.goodsServiceList.map((item) => {
          if (isGoods && isSreve) {
            sum += parseFloat(item[priceKey]) * item.count
          } else if (isGoods && item.goodsRuleType === 1) {
            sum += parseFloat(item[priceKey]) * item.count
          } else if (isSreve && item.goodsRuleType === 2) {
            sum += parseFloat(item[priceKey]) * item.count
          }
        })
      })
      if (!isGoods || !isSreve) {
        if (isGoods) {
          this.productList.map((item) => {
            sum += parseFloat(item.productPrice) * item.productCount
          })
        }

        if (isSreve) {
          this.serveList.map((item) => {
            sum += parseFloat(item.servicePrice) * item.serviceCount
          })
        }
      }

      return parseFloat(sum)
    },

    // 切换支付收款码
    tabPayChange(i) {
      this.payTitleIndex = i
      if (i !== 2) {
        let s = {
          0: 'aliqrcode',
          1: 'wxqrcode',
        }
        this.$nextTick(() => {
          this.$refs[s[this.payTitleIndex]]._makeCode()
        })
      }
    },

    // 删除订单
    delOrder() {
      uni.showModal({
        title: '确认删除该订单？',
        content: '此操作不可撤销',
        confirmColor: '#FBB000',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '已删除',
            })
            let t = setTimeout(() => {
              clearTimeout(t)
              uni.redirectTo({
                url: '/pages_afterSales/arrivalRecordList/arrivalRecordList',
              })
            }, 1000)
          }
        },
      })
    },

    // 二维码事件，储存生成的二维码
    qrResult(data) {
      if (this.payqrImg.length === 2) return false
      this.payqrImg.push({
        type: this.payTitleIndex,
        img: data,
      })
    },

    // 跳转到选择卡券列表页面
    goCouponPage(tab) {
      // if (!this.hasCoupon) return
      // if (this.detailData.statusStr !== '待提交') return
      // uni.navigateTo({
      //   url: '/pages_afterSales/myCoupon/index?status=' + tab,
      //   success: () => {
      //     let t = setTimeout(() => {
      //       clearTimeout(t)
      //       // 发送订单详情事件
      //       uni.$emit('orderDetailChange', {
      //         products: this.productList,
      //         serveList: this.serveList,
      //         discountTotalAmount: this.detailData.couponsAllMoney,
      //       })
      //     }, 500)
      //   },
      // })
      // if (tab) {
      //   uni.navigateBack({
      //     delta: 1,
      //   })
      // } else {
      //   uni.navigateTo({
      //     url: '/pages_afterSales/myCoupon/index?status=' + tab,
      //   })
      // }
    },

    // 获取优惠券列表数据
    async getCouponList() {
      try {
        const res = await this.$api.afterSales.GetCouponList({
          coupon_class: 0,
          pageIndex: 1,
          pageSize: 10,
          mobile: this.$store.state.afterSales.arrvialPhone,
        })

        // 优惠券列表是否含有卡券
        this.hasCoupon = res.data.list.length !== 0
      } catch (e) {
        console.log(e)
      }
    },

    // 提交
    async submit() {
      if (!this.groupList.length) {
        uni.showToast({
          title: '请添加商品或服务',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      uni.showLoading()
      let data = {
        accountId: this.$store.state.afterSales.userId,
        carNum: this.$store.state.afterSales.carInfo.carbrand,
        arriveId: this.id,
        groupList: this.groupList,
        couponAllMoney: this.priceData.couponAllMoney,
        allMoney: this.priceData.allMoney,
        method: 0, //(0、到店安装 1、无需安装)
        reason: this.remark,
        products: this.productList.map((item) => ({
          productId: item.productId,
          productName: item.productName,
          costPrice: item.productPrice,
          rateIncrease: item.addRange,
          count: item.productCount,
          couponId: item.couponId,
          couponMoney: item.couponMoney,
          productTypeId: item.goodsTypeId,
          actuallyAmount: item.productPrice,
        })),
        services: this.serveList.map((item) => ({
          serviceTypeId: item.serviceId,
          serviceName: item.serviceName,
          servicePrice: Number(item.servicePrice),
          serviceCount: item.serviceCount,
          couponId: item.couponId,
          couponMoney: item.couponMoney,
        })),
      }

      try {
        const res = await this.$api.afterSales.createQuotationByCoupon(data)
        uni.showToast({
          title: '提交成功',
          duration: 2000,
        })
        setTimeout(() => {
          uni.redirectTo({
            url:
              '/pages_afterSales/submitOrderDetail/submitOrderDetail?id=' +
              res.data +
              '&isSubmit=0',
          })
        }, 2000)
        // this.userConfirm(res.data)
      } catch (err) {
        console.log(err)
      }
      uni.hideLoading()
    },

    //上传收据图片
    choosePic() {
      const _this = this
      uni.showActionSheet({
        itemList: ['拍照', '打开相册'],
        success(res) {
          const cameraType = res.tapIndex ? 'album' : 'camera'
          uni.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [cameraType], // 从相册选择
            success: function (result) {
              uni.showLoading({
                title: '图片上传中~',
              })
              _this.$api.files
                .uploadImg({
                  filePath: result.tempFilePaths[0],
                })
                .then((res) => {
                  // res.baseUrl + res.url
                  _this.billImg = res.baseUrl + res.url
                  uni.hideLoading()
                })
                .catch((err) => {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片上传失败，请稍后重试',
                    icon: 'none',
                  })
                })
            },
          })
        },
      })
    },

    //现金支付提交
    cashPayments() {
      if (!this.billImg || this.billImg === '/static/img/afterSales/piao.png') {
        uni.showToast({
          title: '请上传收据',
          icon: 'none',
        })
        return
      }

      this.$api.afterSales
        .cashPayments({
          cashReceiptsImg: this.billImg,
          cashReceiptsImg_Note: this.billRemark,
          quotationId: this.detailData.quotationId,
        })
        .then((res) => {
          if (res.data) {
            uni.showToast({
              title: '提交成功',
            })
          }
          this.getDetailData()
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
